package com.adcc.loadsheet.monitor.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.monitor.congifuration.RestartServiceConfiguration;
import com.adcc.loadsheet.monitor.entity.User;
import com.adcc.loadsheet.monitor.service.LoginService;
import com.adcc.loadsheet.monitor.util.Constant;
import com.adcc.loadsheet.monitor.util.SystemConfigFactory;
import com.google.common.base.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * 登录Controller
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService service;


    @Autowired
    private SystemConfigFactory systemConfigFactory;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpSession session) {
        try {
            Optional<User> optional = service.verifyUser(username, password);
            if (optional.isPresent()) {
                // 状态代码为0表示登录成功
                if(optional.get().getCode() == 0){
                    session.setAttribute("user", optional.get());
                    session.setAttribute("roleDisable", systemConfigFactory.getRoleDisable().get("roleDisable"));
                    return "redirect:index";
                }else{
                    model.addAttribute("errorMsg", optional.get().getReason());
                    return "login";
                }
            } else {
                model.addAttribute("errorMsg", Constant.ERROR_SERVER);
                return "login";
            }
        } catch (Exception ex) {
            Log.error(LoginController.class, "login() error", ex);
            model.addAttribute("errorMsg", Constant.ERROR_SERVER);
            return "login";
        }
    }
}
